<template>
  <u-view class="container">
    <!-- 标题栏 -->
    <u-navbar title="电站管理" :autoBack="false">
      <template #right>
        <u-icon name="plus" size="20" color="#fff" @click="addNewItem"></u-icon>
      </template>
    </u-navbar>

    <!-- 搜索和筛选区域 -->
    <view class="search-filter-container">
      <u-search
        v-model="searchQuery"
        placeholder="请输入电站联系人/编号"
        :showAction="false"
        @search="applyFilters"
        @clear="applyFilters"
      ></u-search>
      
      <u-button 
        size="mini" 
        plain 
        @click="toggleFilterModal"
        customStyle="margin-left:10px;height:36px"
      >
        <u-icon name="filter" size="14" color="#606266"></u-icon>
        <text>筛选</text>
      </u-button>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup 
      v-model="showFilterModal" 
      mode="bottom" 
      :closeable="true"
      title="筛选条件"
    >
      <view class="filter-content">
        <view class="filter-section">
          <text class="section-title">状态</text>
          <u-radio-group 
            v-model="filterStatus"
            placement="row"
            @change="applyFilters"
          >
            <u-radio 
              v-for="(item, index) in statusOptions" 
              :key="index"
              :name="item.value"
              :label="item.label"
              customStyle="margin-right:15px"
            ></u-radio>
          </u-radio-group>
        </view>

        <view class="filter-section">
          <text class="section-title">地区选择</text>
          <u-picker 
            :columns="range"
            v-model="value"
            @confirm="confirmArea"
            @cancel="cancelArea"
          ></u-picker>
        </view>
      </view>
    </u-popup>

    <!-- 电站列表 -->
    <u-list
      v-if="owners.length > 0"
      :height="scrollViewHeight"
      @scrolltolower="loadMore"
    >
      <u-list-item
        v-for="(owner, index) in owners"
        :key="index"
      >
        <u-card 
          :title="owner.guestname"
          :subTitle="`编号: ${owner.stationno}`"
          @click="navigateToDetail(owner.id)"
        >
          <view slot="body">
            <u-row>
              <u-col span="2">
                <u-icon name="map" size="16" color="#909399"></u-icon>
              </u-col>
              <u-col span="10">
                <text class="info-text">{{ owner.addressstring }}</text>
              </u-col>
            </u-row>
            
            <u-row class="info-row">
              <u-col span="2">
                <u-icon name="calendar" size="16" color="#909399"></u-icon>
              </u-col>
              <u-col span="10">
                <text class="info-text">{{ formatDate(owner.createTime) }}</text>
              </u-col>
            </u-row>
          </view>
          
          <view slot="foot">
            <u-tag 
              :text="getStatusText(owner.status)"
              :type="getStatusType(owner.status)"
              size="mini"
              customStyle="margin-right:10px"
            ></u-tag>
            
            <u-button 
              size="mini" 
              plain 
              @click.stop="handleCall(owner.phone)"
            >
              <u-icon name="phone" size="12"></u-icon>
              <text>拨打</text>
            </u-button>
            
            <u-button 
              size="mini" 
              plain 
              type="primary"
              @click.stop="fetchStationCoordinates(owner.id)"
              customStyle="margin-left:10px"
            >
              <u-icon name="map-pin" size="12"></u-icon>
              <text>导航</text>
            </u-button>
          </view>
        </u-card>
      </u-list-item>
    </u-list>

    <!-- 空状态 -->
    <u-empty
      v-else
      mode="data"
      icon="http://cdn.uviewui.com/uview/empty/data.png"
      text="暂无电站数据"
    ></u-empty>
  </u-view>
</template>

<script>
import request from '@/utils/request.js';
import { getAccessToken } from '@/utils/auth';
import { tansParams } from '@/utils/common';

export default {
  data() {
    const token = getAccessToken();
    return {
      token,
      searchQuery: "",
      owners: [],
      scrollViewHeight: 0,
      showFilterModal: false,
      filterStatus: "",
      statusOptions: [
        { label: "全部", value: "" },
        { label: "在线", value: "1" },
        { label: "离线", value: "2" },
        { label: "待定", value: "3" }
      ],
      provinces: [],
      cities: {},
      areas: {},
      range: [],
      value: [],
      selectedValue: [],
      selectedAreaText: "",
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false
    };
  },
  methods: {
    async applyFilters() {
      this.page = 1;
      this.finished = false;
      const queryParams = {
        pageNum: this.page,
        pageSize: this.pageSize
      };
      
      if (this.filterStatus) queryParams.status = this.filterStatus;
      if(this.selectedValue.length > 0) {	
        queryParams.provinceId = this.provinces[this.selectedValue[0]].id;
        queryParams.cityId = this.cities[queryParams.provinceId][this.selectedValue[1]].id;
        queryParams.areaId = this.areas[queryParams.cityId][this.selectedValue[2]].id;
      }

      const queryString = tansParams(queryParams);
      const url = `/oper/station/page?${queryString}`; 
      
      try {
        const response = await request({
          url: url,	  
          method: 'GET',
          headers: { Authorization: `Bearer ${this.token}` }
        });
        
        this.owners = response.data.list || [];
        
        if (this.searchQuery) {
          const keywords = this.searchQuery.split(/\s+/).map(keyword => keyword.toLowerCase());
          this.owners = this.owners.filter(owner => {
            return keywords.some(keyword =>
              owner.guestname.toLowerCase().includes(keyword) ||
              owner.stationno.toLowerCase().includes(keyword) ||
              owner.addressstring.toLowerCase().includes(keyword)
            );
          });
        }
      } catch (error) {
        this.$u.toast('获取数据失败');
        console.error("API 请求失败", error);
      }
    },
    
    async loadMore() {
      if (this.finished || this.loading) return;
      
      this.loading = true;
      this.page++;
      
      const queryParams = {
        pageNum: this.page,
        pageSize: this.pageSize
      };
      
      if (this.filterStatus) queryParams.status = this.filterStatus;
      if(this.selectedValue.length > 0) {	
        queryParams.provinceId = this.provinces[this.selectedValue[0]].id;
        queryParams.cityId = this.cities[queryParams.provinceId][this.selectedValue[1]].id;
        queryParams.areaId = this.areas[queryParams.cityId][this.selectedValue[2]].id;
      }

      try {
        const response = await request({
          url: `/oper/station/page?${tansParams(queryParams)}`,
          method: 'GET',
          headers: { Authorization: `Bearer ${this.token}` }
        });
        
        const newData = response.data.list || [];
        if (newData.length > 0) {
          this.owners = [...this.owners, ...newData];
        } else {
          this.finished = true;
        }
      } catch (error) {
        console.error("加载更多失败", error);
      } finally {
        this.loading = false;
      }
    },
    
    toggleFilterModal() {
      this.showFilterModal = !this.showFilterModal;
    },
    
    resetFilters() {
      this.filterStatus = "";
      this.searchQuery = "";
      this.selectedValue = [];
      this.selectedAreaText = "";
      this.value = [0, 0, 0];
      this.fetchAllOwners();
    },

    navigateToDetail(stationId) {
      this.$u.route('/pages/work/PSM/PSDetails/index', {
        id: stationId
      });
    },
    
    getStatusText(status) {
      return status === 1 ? "在线" : status === 2 ? "离线" : "待定";
    },
    
    getStatusType(status) {
      return status === 1 ? "success" : status === 2 ? "error" : "warning";
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      return this.$u.timeFormat(timestamp, 'yyyy-mm-dd');
    },
    
    handleCall(phone) {
      if (!phone) {
        this.$u.toast('无联系电话');
        return;
      }
      this.$u.makePhoneCall(phone);
    },
    
    async fetchStationCoordinates(stationId) {
      try {
        const response = await request({
          url: `/oper/station/get?id=${stationId}`,
          method: "GET",
          headers: { Authorization: `Bearer ${this.token}` },
        });

        const { latitude, longitude } = response.data || [];
        
        if (latitude && longitude) {
          this.$u.route({
            type: 'openLocation',
            latitude: Number(latitude),
            longitude: Number(longitude),
            name: "电站位置",
            address: "请使用地图查看详细位置",
            scale: 18
          });
        } else {
          this.$u.toast('未获取到位置信息');
        }
      } catch (error) {
        console.error('获取电站经纬度失败:', error);
        this.$u.toast('获取位置失败');
      }
    },
    
    addNewItem() {
      this.$u.route('/pages/work/PSM/PSCreate/index');
    },  
    
    async fetchAreas() {
      try {
        const response = await request({
          url: "/system/area/tree",
          method: 'GET',
          headers: { Authorization: `Bearer ${this.token}` }
        });
    
        const areaData = response.data;
        this.provinces = areaData.map(province => ({
          id: province.id,
          name: province.name,
        }));
        
        this.cities = {};
        this.areas = {};
    
        areaData.forEach((province) => {
          this.cities[province.id] = province.children.map((city) => ({
            id: city.id,
            name: city.name,
          }));
          
          province.children.forEach((city) => {
            this.areas[city.id] = city.children.map((area) => ({
              id: area.id,
              name: area.name,
            }));
          });
        });

        // 转换为uPicker需要的格式
        this.range = [
          this.provinces.map(p => ({ label: p.name, value: p.id })),
          this.cities[this.provinces[0].id].map(c => ({ label: c.name, value: c.id })),
          this.areas[this.cities[this.provinces[0].id][0].id].map(a => ({ label: a.name, value: a.id }))
        ];
      } catch (error) {
        console.error('获取地区数据失败:', error);
      }
    },
    
    confirmArea(e) {
      this.selectedValue = e.value;
      this.selectedAreaText = e.label.join(' ');
      this.applyFilters();
      this.showFilterModal = false;
    },
    
    cancelArea() {
      this.showFilterModal = false;
    },
     
    async fetchAllOwners() {
      try {
        const response = await request({
          url: `/oper/station/page?pageSize=100`,
          method: 'GET',
          headers: { Authorization: `Bearer ${this.token}` }
        });
        this.owners = response.data.list || [];
      } catch (error) {
        this.$u.toast('获取数据失败');
        console.error("获取所有电站数据失败", error);
      }
    },
    
    calculateScrollViewHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.container').boundingClientRect(data => {
        const systemInfo = uni.getSystemInfoSync();
        const windowHeight = systemInfo.windowHeight;
        const containerTop = data.top;
        this.scrollViewHeight = windowHeight - containerTop - 10;
      }).exec();
    }
  },
  
  mounted() {
    this.fetchAreas();
    this.fetchAllOwners();
    this.calculateScrollViewHeight();
    
    uni.onWindowResize(() => {
      this.calculateScrollViewHeight();
    });
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 12px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.search-filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.filter-content {
  padding: 15px;
}

.filter-section {
  margin-bottom: 20px;
  
  .section-title {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;
  }
}

.info-row {
  margin-bottom: 8px;
}

.info-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}
</style>